package com.springboot.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.springboot.dto.CacheDto;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

@Component
@Service
public class demo1 implements ApplicationContextAware {

    private static List<String[]> user1_keywords = new ArrayList<String[]>();
    private static String user1_token = "UID_seNKM3Lwu9qLEZVHR3cncKYyXPqS";
    private static String user1_name = "赵大宝";
    private static List<CacheDto> sessionDtoList = new ArrayList<CacheDto>();
    private static Map<String, String> cacheMap = new HashMap<String, String>();

    private static List<String> host = new ArrayList<String>();
    private static List<String> port = new ArrayList<String>();

    public static void setKeyWord(){

        String[] aaa = {"12700+3080ti","100015259355"};
        user1_keywords.add(aaa);
        String[] bbb = {"5800+3070ti","100015189221"};
        user1_keywords.add(bbb);
        String[] ccc = {"12600+3060ti","100028031354"};
        user1_keywords.add(ccc);
        String[] ddd = {"5800+3060","100029913338"};
        user1_keywords.add(ddd);
        String[] eee = {"11600+3060ti","100015196519"};
        user1_keywords.add(eee);
        String[] fff = {"11400+3060","100015196493"};
        user1_keywords.add(fff);

    }

    public static void setProxy(){
        host.add("36.57.89.86");
        port.add("8888");
        host.add("202.116.32.236");
        port.add("80");
        host.add("182.140.244.163");
        port.add("8118");
        host.add("222.129.39.38");
        port.add("57114");
        host.add("47.103.125.129");
        port.add("8080");
    }



    @Scheduled(cron = "0 0/1 * * * ?")
    public static void get_data(){
        setProxy();
        setKeyWord();
        System.out.println(cacheMap.size());

        //使用代理ip后，会报错
//        Random r = new Random();
//        int num = r.nextInt(5);
//        System.out.println(num);
//        System.out.println(host.get(num));
//        System.out.println(port.get(num));
//        System.setProperty("proxyHost",host.get(num));
//        System.setProperty("proxyPort",port.get(num));

        String user = user1_name;
        String mail = user1_token;
        List<String[]> keyword=user1_keywords;
        get_products(user,keyword);
        log(user,mail);
    }

    public static void get_products(String user,List<String[]> user1_keywords){
        List<String[]> skuids = user1_keywords;
        String base_url = "https://wq.jd.com/mjgj/bigcommsub/QueryCommStockByArea?skuids=";
        String en_url="&channel=3&province=12&city=988&county=47821&_=1643395274237&sceneval=2&g_login_type=1&callback=jsonpCBKG&g_ty=ls";
        String sku_id="";

        if (skuids.size() > 1){
            String sku_id2="";
            for (int i = 0; i < skuids.size(); i++) {
                String value = skuids.get(i)[1];
                sku_id2 += value + "%2C";
            }
            sku_id = sku_id2.substring(0,sku_id2.length()-3);
        }else{
            String value = skuids.get(0)[1];
            sku_id = value;
        }
        String url = base_url + sku_id + en_url;
        //System.out.println(url);

        HttpResponse res = HttpRequest.get(url).contentType("application/json").execute();//findToken是这个url的token信息，如果不需要就不写,contentType具体看url中需要的是什么类型
        String resp_body_string = res.body().toString();
        String resp_body_sub = resp_body_string.substring(14,resp_body_string.length()-13);
        //System.out.println(resp_body_sub);
        JSONObject jsobj = new JSONObject(resp_body_sub);
        //System.out.println(jsobj);
        JSONArray jsonArray= jsobj.getJSONArray("res");
        //System.out.println(jsonArray);

        for(int t=0;t<jsonArray.size();t++){
            JSONObject object = jsonArray.getJSONObject(t);
            //System.out.println(object);
            String id = object.get("skuid").toString();
            //System.out.println(id);
            JSONObject stock = object.getJSONObject("stock");
            //System.out.println(stock);
            String value = stock.get("a").toString();
            System.out.println(value);

            //String msg = "";
            CacheDto sessionDto = new CacheDto();
            if(value.equals("33")){
                //msg = getNameByCode(id)+"有货";
                sessionDto.setCode(id);
                sessionDto.setStatus("有货");
                sessionDto.setName(getNameByCode(id));
            }else if (value.equals("34")){
                //msg = getNameByCode(id)+"无货";
                sessionDto.setCode(id);
                sessionDto.setStatus("无货");
                sessionDto.setName(getNameByCode(id));
            }else{
                //get_data();
                //msg = "未知状态，程序异常";
                //wxpush(content,user,user1_token);
            }
            sessionDtoList.add(sessionDto);

        }

        //r = requests.get(url,timeout=10)
        //skuids = json.loads(r.text[14:-14])

    }

    public static String getNameByCode(String code) {
        String name = "";
        for (String[] user1_keyword : user1_keywords) {
            if(user1_keyword[1].equals(code)){
                name = user1_keyword[0];
            }
        }
        return name;
    }

    public static void log(String user,String mail) {
        //进行状态对比，将那个库存变化了 就进行推送操作
        String content = "12700+3080ti 有货";
        for (CacheDto sessionDto : sessionDtoList) {
            String thisCode = sessionDto.getCode();
            String thisStatus = sessionDto.getStatus();
            String thisName = sessionDto.getName();
            if(cacheMap.get(thisCode) != null){
                if(!cacheMap.get(thisCode).equals(thisStatus)){
                    //两次状态不相同，存储这个code，覆盖缓存
                    content = content + thisName + "\r\n";
                    cacheMap.put(thisCode, thisStatus);
                }else{
                    //两次状态相同,不做操作
                }
            }else{
                cacheMap.put(thisCode, thisStatus);
            }
        }
        if(!content.equals("")){
            boolean successOrFailure = wxpush(content,user,mail);
            if(successOrFailure){
                System.out.println("微信推送发送成功");
            }else{
                System.out.println("微信推送发送失败");
            }
        }
        System.out.println("over");
    }

    public static boolean wxpush(String content,String user,String mail){
        boolean state = false;

        try {
            String url_json = "http://wxpusher.zjiecode.com/api/send/message";
            JSONObject header = new JSONObject();
            header.set("Host","wxpusher.zjiecode.com");
            header.set("User-Agent","Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0");
            header.set("Accept","*/*");
            header.set("Accept-Encoding","gzip, deflate, br");
            header.set("Connection","keep-alive");
            header.set("Content-Length","221");
            header.set("Cache-Control","max-age=0");
            header.set("Content-Type","application/json");

            JSONObject data = new JSONObject();
            data.set("appToken","AT_yhoCXrGr9Tkt17bQUSyv6mXMNYafgdHj");
            //data.set("appToken",userToken);
            data.set("content",content);
            data.set("summary",user + ",您关注的物品状态变化\r\n" + content);//消息摘要，显示在微信聊天页面或者模版消息卡片上，限制长度100，可以不传，不传默认截取content前面的内容。
            data.set("contentType",1);//内容类型 1表示文字  2表示html(只发送body标签内部的数据即可，不包括body标签) 3表示markdown
            //data.set("topicIds","[]");//发送目标的topicId，是一个数组！！！，也就是群发，使用uids单发的时候， 可以不传。
            String[] aa = new String[1];
            aa[0] = "UID_seNKM3Lwu9qLEZVHR3cncKYyXPqS";
            data.set("uids",aa);//发送目标的UID，是一个数组。注意uids和topicIds可以同时填写，也可以只填写一个。//   "url":"http://wxpusher.zjiecode.com" //原文链接，可选参数

            String postResult = HttpRequest
                    .post(url_json)
                    .header("Host","wxpusher.zjiecode.com")
                    .header("User-Agent","Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0")
                    .header("Accept","*/*")
                    .header("Accept-Encoding","gzip, deflate, br")
                    .header("Connection","keep-alive")
                    .header("Content-Length","221")
                    .header("Cache-Control","max-age=0")
                    .header("Content-Type","application/json")
                    .body(data.toString())
                    .execute()
                    .body();
            state = true;
        }catch (Exception e){

        }

        return state;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }

/*    public static void main(String[] args) {
        //首先访问申请获取状态，然后跟缓存中的状态进行对比，状态改变执行微信推送
        setKeyWord();
        get_data();
    }*/

}
